import React, { useState, useEffect } from "react"
import styled from "styled-components"
import { Link, useNavigate } from "react-router-dom"
import Logo from "../assets/logo.svg"
import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"
import axios from "axios"
import { registerRoute } from "../utils/APIRoutes"

export default function Register() {
  const navigate = useNavigate()

  const [values, setValues] = useState({
    username: "",
    email: "",
    password: "",
    confirmPassword: "",
  })

  const toastOptions = {
    position: "bottom-right",
    autoClose: 5000,
    pauseOnHover: true,
    draggable: true,
    hideProgressBar: true,
    theme: "dark",
  }

  useEffect(() => {
    if (localStorage.getItem("snappy-user")) {
      navigate("/")
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const handleSubmit = async (event) => {
    event.preventDefault()
    if (handleValidation()) {
      const { username, email, password } = values
      await axios
        .post(registerRoute, {
          username,
          email,
          password,
        })
        .then((res) => {
          if (res.data.status) {
            localStorage.setItem("snappy-user", JSON.stringify(res.data.user))
            navigate("/")
          } else {
            toast.error(res.data.msg, toastOptions)
          }
        })
        .catch(() => {
          toast.error("Unknown error.", toastOptions)
        })
    }
  }

  const handleChange = (event) => {
    // 实际上是对 values 对象进行展开，之后再对相应的属性进行覆写
    setValues({ ...values, [event.target.name]: event.target.value })
  }

  const handleValidation = () => {
    const { username, email, password, confirmPassword } = values
    if (username.length < 3 || username.length > 20) {
      toast.warning("Username should be 3 ~ 20 characters.", toastOptions)
      return false
    } else if (email === "") {
      toast.warning("Eamil is required.", toastOptions)
      return false
    } else if (password.length < 8 || password.length > 20) {
      toast.warning("Password should be 8 ~ 20 characters.", toastOptions)
      return false
    } else if (password !== confirmPassword) {
      toast.warning("Password and confirm password do not match.", toastOptions)
      return false
    }
    return true
  }

  return (
    // 空标签，相当于 vue 中的 template，便于同时返回多个元素
    <>
      <FormContainer>
        <form onSubmit={(event) => handleSubmit(event)}>
          <div className="brand">
            <img src={Logo} alt="Logo" />
            <h1>snappy</h1>
          </div>
          <input
            type="text"
            placeholder="Username"
            name="username"
            onChange={(event) => handleChange(event)}
          />
          <input
            type="email"
            placeholder="Email"
            name="email"
            onChange={(event) => handleChange(event)}
          />
          <input
            type="password"
            placeholder="Password"
            name="password"
            onChange={(event) => handleChange(event)}
          />
          <input
            type="password"
            placeholder="Confirm Password"
            name="confirmPassword"
            onChange={(event) => handleChange(event)}
          />
          <button type="submit">Create User</button>
          <span>
            Already have an account ? <Link to="/login">Login</Link>
          </span>
        </form>
      </FormContainer>
      <ToastContainer />
    </>
  )
}

const FormContainer = styled.div`
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  background-color: #131324;

  .brand {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 1rem;
    h1 {
      color: white;
      text-transform: uppercase;
    }
    img {
      height: 5rem;
    }
  }

  form {
    display: flex;
    flex-direction: column;
    gap: 2rem;
    background-color: #00000076;
    border-radius: 2rem;
    padding: 3rem 5rem;

    input {
      background-color: transparent;
      padding: 1rem;
      border: 0.1rem solid #4e0eff;
      border-radius: 0.4rem;
      color: white;
      width: 100%;
      font-size: 1rem;
      &:focus {
        border: 0.1rem solid #997af0;
        outline: none;
      }
    }

    button {
      background-color: #997af0;
      color: white;
      padding: 1rem 2rem;
      border: none;
      font-weight: bold;
      cursor: pointer;
      border-radius: 0.4rem;
      text-transform: uppercase;
      font-size: 1rem;
      transition: 1s ease-in-out;
      &:hover {
        background-color: #4e0eff;
      }
    }

    span {
      color: white;
      text-transform: uppercase;
      a {
        color: #4e0eff;
        text-decoration: none;
        font-weight: bold;
      }
    }
  }
`
